package com.farmer.h5.util;

import java.io.File;

import android.content.Context;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;

public class WebViewCacheUtil
{
    /**
     * 清除本地手机上面的缓存文件
     */
    public static int clearCacheFolder(File dir, long numDays)
    {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory())
        {
            try
            {
                for (File child : dir.listFiles())
                {
                    if (child.isDirectory())
                    {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }
                    if (child.lastModified() < numDays)
                    {
                        if (child.delete())
                        {
                            deletedFiles++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }
    
    /**
     * 清除webview缓存
     * 
     * @param webView
     */
    public static void clearCache(WebView webView)
    {
        webView.clearCache(true);
    }
    
    /**
     * 清除cookies
     * @param context
     */
    public static void clearCookies(Context context)
    {
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }
    
    /**
     * 同步一下cookie
     */
    public static void synCookies(Context context, String url)
    {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除
        // cookieManager.setCookie(url, cookies);//指定要修改的cookies
        CookieSyncManager.getInstance().sync();
    }
    
    /**
     *  在退出应用的时候使用
     */
    public static void clear4Exit(Context context)
    {
        File file = context.getCacheDir();
        if (file != null && file.exists() && file.isDirectory())
        {
            for (File item : file.listFiles())
            {
                item.delete();
            }
            file.delete();
        }
        context.deleteDatabase("webview.db");
        context.deleteDatabase("webviewCache.db");
    }
}
